package com.mobile.framework.entity;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import java.io.Serializable;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;

/**
 * Base class for Model objects. This is basically for the toString, equals and
 * hashCode methods.
 */
public class BaseEntity implements Serializable {
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this,
				ToStringStyle.MULTI_LINE_STYLE);
	}
	
	public BaseEntity(){
		
	}

	public boolean equals(Object o) {
		return EqualsBuilder.reflectionEquals(this, o);
	}
	/*while one-many cascade,throws org.hibernate.LazyInitialization:illegal accesss to loading collection,so annotate it*/
	public int hashCode() {

        //参考HashCodeBuilder.reflectionHashCode(17, 37, object, false, null, String[] excludeFields) 实现
        Field[] fields = this.getClass().getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        String[] excludeFields = new String[]{};
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
             if(field.getType().toString().equals("interface java.util.Set")){
               excludeFields= (String[])ArrayUtils.add(excludeFields,field.getName());
//                 System.out.println("####excludeFields####"+field.getName());
            }
        }
        return HashCodeBuilder.reflectionHashCode(17, 37, this, false, null, excludeFields.length==0?null:excludeFields);
//        return HashCodeBuilder.reflectionHashCode(this);
	}
}
